package com.liveims.webims.session;

import java.util.List;

import org.apache.log4j.Logger;

import com.alcatel.as.session.distributed.Session;
import com.alcatel.as.session.distributed.SessionException;
import com.alcatel.as.session.distributed.SessionManager;
import com.alcatel.as.session.distributed.SessionType;
import com.alcatel.as.session.distributed.Transaction;

import com.alcatel.as.session.distributed.SessionManager.AddSessionListenerCallback;
import com.alcatel.as.session.distributed.event.SessionEventFilter;
import com.alcatel.as.session.distributed.event.SessionListener;
import com.liveims.webims.util.WimsMessage;

public class IMSManager {

    private final static Logger LOGGER = Logger.getLogger(IMSManager.class);

    // Our Distributed Sessions Manager
    private static SessionManager _dsManager = SessionManager.getSessionManager();
   
    // Our distributed session name
    public final static String SESSION_ADMIN_TYPE = "IMSWEB2";

    // Our distributed session type
    public static SessionType _convergenceSessionType = _dsManager.getSessionType(SESSION_ADMIN_TYPE);

    // Our distributed session Attribute
    public  final static String IM_ATTRIBUTE = "message";
	public  final static String Presence_ATTRIBUTE = "presence";
	
    // Our instance in JVM
    private static IMSManager _instance = null;
    
    private IMSManager() {
    }

    /**
     * Return the static instance of IMSManager
     * 
     * @return the instance
     */
    public static IMSManager getInstance() {
        if (_instance == null) {
            _instance = new IMSManager();
        }
        return _instance;
    }

    /**
     * Adds a new SessionListener to our convergence distributed session
     * 
     * @param listener
     *            the new listener
     * @param sid 
     *            the session identifier
     * @param f 
     *            the sessionEventFilter
     * @throws SessionException 
     */
    public void addListener(SessionListener listener,  String sid, AddSessionListenerCallback callback) {
        _dsManager.addSessionListener(_convergenceSessionType,
                sid, listener,
                new SessionEventFilter(
                SessionEventFilter.ACCEPT_ALL_ATTRIBUTES,
                SessionEventFilter.EVENT_ATTRIBUTE_ALL), callback);
    }

    /**
     * Removes a SessionListener from our convergence distributed session
     * 
     * @param listenerId
     * the listener id
     */
    public void removeListener(int listenerId) {
        _dsManager.removeSessionListener(listenerId);
    }
    
    public String createSession (String user) throws SessionException{
    	
    	final String sid = user; //fake, supposed to be replaced by a key generator
    	Transaction tr = new Transaction(_convergenceSessionType,
				                          sid,
				                          Transaction.TX_CREATE_GET){
		    private static final long serialVersionUID = 1L;
			public void execute(Session session) throws SessionException {
    			if (session == null) {return;
    			}else if(session.created()){	
    			session.commit(sid);
    			}
       		}
    	};
	   String resu = (String)_dsManager.execute(tr);
	   LOGGER.debug(" IMS REG Session create result " + resu);
	   return resu;
    	
    }
    
    public static boolean hasSession (String sid){
       try {
			List<Session> sessionList = _dsManager.getSessions(_convergenceSessionType);
			for (Session s : sessionList){
				if (s.getSessionId().equals(sid))
					return true;
			}
		} catch (SessionException e) {			
			e.printStackTrace();
			return false;
		}
    	
    	return false;
    }
    
    public void updateSessionAttribute(String sid, String attriName, WimsMessage m) throws SessionException{
    	final String name = attriName;
    	final WimsMessage tm = m;
    	Transaction tr = new Transaction(_convergenceSessionType, sid, Transaction.TX_GET)
    	                 {
							private static final long serialVersionUID = -7694563705616478338L;
								@Override
								public void execute(Session session)throws SessionException {
								    session.setAttribute(name, tm);
								    LOGGER.info("session attribute set "+ name);
								    session.commit(null);
								}
     	                  };
     	_dsManager.execute(tr);
    	
    }
}
